package com.cochain.ftp;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.FtpException;
import org.springframework.stereotype.Service;


import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @title: MutilFtpClientPool
 * @Description: 多ftp服务器池
 * @Author Lmm
 * @Date: 2024/3/29 9:15
 * @Version 1.0
 */
@Service
public class DefaultMultiFtpClientPool implements MultiFtpClientPoolFun<FtpClientPool> {
    private final Map<String,FtpClientPool> multiPool = new ConcurrentHashMap<>(16);

    /**
     * 不同的ftp服务器客户端池 在构造的时候可以调用该方法把自己放进来
     */
    public void initPool(String flag,FtpClientPool clientPool){
        if (StrUtil.isBlank(flag))
            throw new FtpException("param :flag  must not be '' or null");
        if (null == clientPool)
            throw new FtpException("param :clientPool must not be  null");
        multiPool.putIfAbsent(flag, clientPool);
    }
    /**
     * @param flag {@link #initPool(String, FtpClientPool)}方法传进来的flag
     * 获取客户端池
     * （1）如果给了flag标识，优先返回对应池
     *  如果对应池不存在，则随机返回一个池
     * （2）如果flag标识为null，则则随机返回一个池
     */
    public FtpClientPool getPool(String flag){
        if (StrUtil.isBlank(flag)){
            return getRandomClientPool();
        }
        if (multiPool.containsKey(flag))
            return multiPool.get(flag);
        return getRandomClientPool();
    }
    /**
     * 随机获取一个ftp 客户端池
     */
    private FtpClientPool getRandomClientPool() {
        Object[] multiPoolArray = Arrays.stream(multiPool.values().toArray()).toArray();
        Random random = new Random();
        int next = random.nextInt(multiPoolArray.length);
        return (FtpClientPool)multiPoolArray[next];
    }

}

